package com.github.util;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.bean.ServerUser;
import com.github.bean.ServerUserSession;
import com.github.common.constant.MyConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@Configuration
public class SocketSendThread {
    // 在控制器或服务中添加测试
    private static final Logger logger = LoggerFactory.getLogger(SocketSendThread.class);

    // 用于存储每个 WebSocketSession 对应的消息队列
    public static final ConcurrentHashMap<String, BlockingQueue<String>> sessionQueues = new ConcurrentHashMap<>();

    public void add(WebSocketSession session) {
        // 为新建立的 WebSocketSession 创建一个消息队列
        BlockingQueue<String> messageQueue = new LinkedBlockingQueue<>();
        sessionQueues.put(session.getId(), messageQueue);

        // 启动一个单独的线程来处理该会话的消息队列
        new Thread(() -> {
            ServerUserSession userSession = null;
            String account = "";
            while (true) {
                if (userSession == null) {
                    ServerUserSession serverUserSession = SessionSocketHolder.get(session.getId());
                    if (serverUserSession != null) {
                        userSession = serverUserSession;
                        account = userSession.getAccount();
                        synchronized (userSession) {
                            if (userSession != null) {
                                account = userSession.getAccount();
                            }
                        }
                    }
                }
                String message = "";
                try {
                    if (!session.isOpen()) {
                        return;
                    }
                    // 从队列中取出消息
                    message = messageQueue.poll(100, TimeUnit.MILLISECONDS);
                    if (StringUtils.isEmpty(message)) {
                        continue;
                    }
                    if (!message.contains("\"msg_type\":2")) {
                        logger.info("发送数据-->" + account + ";设备状态:" + session.isOpen() + ";内容-->" + message);
                    }
                    if (session.isOpen()) {
                        // 增加同步块，确保线程安全
                        synchronized (session) {
                            if (session.isOpen()) {
                                // 发送消息
                                session.sendMessage(new TextMessage(AESEncrypt.encrypt(message)));
                            } else {
                                return;
                            }
                        }
                    } else {
                        return;
                    }
                } catch (InterruptedException e) {
                    // 线程被中断，退出循环
                    Thread.currentThread().interrupt();
                    return;
                } catch (IOException e) {
                    logger.info("发送数据-->" + account + ";失败,设备状态:" + session.isOpen());
                    // 发生 I/O 异常，检查连接状态
                    if (!session.isOpen()) { //未打开退出
                        return;
                    }
                    e.printStackTrace();
                    //重发
                    if (session.isOpen()) {
                        // 增加同步块，确保线程安全
                        synchronized (session) {
                            if (session.isOpen()) {
                                // 发送消息
                                try {
                                    session.sendMessage(new TextMessage(AESEncrypt.encrypt(message)));
                                    logger.info("发送数据-->" + account + ";重发成功,设备状态:" + session.isOpen());
                                } catch (IOException ioException) {
                                    ioException.printStackTrace();
                                    logger.info("发送数据-->" + account + ";重发失败,设备状态:" + session.isOpen());
                                    if (!session.isOpen()) { //未打开退出
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void remove(WebSocketSession session) {
        sessionQueues.remove(session.getId());
    }

    public static void sendMessage(WebSocketSession session, String msg) {
        BlockingQueue<String> messageQueue = sessionQueues.get(session.getId());
        if (messageQueue != null) {
            try {
                // 将消息放入队列
                messageQueue.put(msg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
